package com.ruoyi.workbench.controller;


import com.alibaba.fastjson2.JSONObject;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.workbench.domain.*;
import com.ruoyi.workbench.dto.*;
import com.ruoyi.workbench.service.*;
import com.ruoyi.workbench.vo.SystemManageVo;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.xmlbeans.impl.regex.REUtil;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.ruoyi.common.core.domain.AjaxResult.success;
import static com.ruoyi.common.utils.PageUtils.startPage;


/**
 * 事项控制器
 */
@RestController
@RequestMapping("/matter")
public class MatterController extends BaseController{


    @Resource
    private WorkMatterService workMatterService;

    @Resource
    private WorkContentService workContentService;

    @Resource
    private WorkCollaborationService workCollaborationService;

    @Resource
    private WorkDialogService workDialogService;

    @Resource
    private WorkMatterPracticableService workMatterPracticableService;

    @Resource
    private WorkReportService workReportService;


    @Resource
    private IWorkTargetService workTargetService;

    @GetMapping("/getRelatedIndicatorOrTask")
    public AjaxResult getRelatedIndicatorOrTask(Integer type) {

        if (type == 0) { //查询指标
            List<RelatedIndicatorOrTaskRequest> list = workMatterService.getTargetTasks();
            return success(list);
        }
        if (type == 1) { // 查询任务
            List<RelatedIndicatorOrTaskRequest> list = workMatterService.getTasks();
            return success(list);
        }

        return AjaxResult.error("type错误");
    }

    @GetMapping("/getUsers")
    public AjaxResult getUsers() {
        List<UsersDTO> users = workMatterService.getUsers();
        return success(users);
    }

    @GetMapping("/updteIsKeyWork")
    public AjaxResult updteIsKeyWork(WorkMatter matter) {
        WorkMatter update = workMatterService.update(matter);
        return success(update);
    }

    @GetMapping("/updateIsFollowed")
    public AjaxResult updateIsFollowed(WorkMatter matter) {
        workMatterService.updteFollowed(matter);
        return success();
    }


    @GetMapping("/getSystemManage")
    public AjaxResult getSystemManage() {
        List<OptionUtile> list = workMatterService.getSystemManage();
        return success(list);
    }


    /**
     * 任务接收列表
     *
     * @param request
     * @param pageDomain
     * @return
     */
    @GetMapping("/listTask")
    public AjaxResult listTask(ListTaskRequest request, PageDomain pageDomain) {
        Long userId = SecurityUtils.getUserId();
        request.setUserId(userId);
        PageInfo<WorkTask> indexList = workMatterService.listTask(request, pageDomain);
        return success(indexList);
    }


    /**
     * 任务认领
     *
     * @param taskId
     * @return
     */
    @GetMapping("/taskClaim")
    public AjaxResult taskClaim(Integer taskId) {

        boolean b = workMatterService.taskClaim(taskId);
        if (b) {
            return success("认领成功");
        }
        return AjaxResult.error("认领失败");
    }

    @GetMapping("/index/list")
    public AjaxResult indexList(WorkMatter matter, PageDomain pageDomain) {
        PageInfo<WorkMatter> indexList = workMatterService.getIndexList(matter, pageDomain);
        return success(indexList);
    }

    @PreAuthorize("@ss.hasPermi('matter:matter:dataScopeMatterList')")
    @GetMapping("/matter/dataScopeMatterList")
    public TableDataInfo dataScopeMatterList(WorkMatter matter) {
        startPage();
        List<WorkMatter> list= workMatterService.getDataScopeMatterList(matter);
        return getDataTable(list);
    }

    @GetMapping("/dialogList")
    public AjaxResult dialogList(WorkMatter matter, PageDomain pageDomain) {
        PageInfo<WorkMatter> indexList = workMatterService.dialogList(matter, pageDomain);
        return success(indexList);
    }
    @GetMapping("/updateDialog")
    public AjaxResult updateDialog(String dialogId,String dialogContent) {
        workMatterService.updateDialog(dialogId,dialogContent);
        return success();
    }

    @GetMapping("/getPracticables")
    public AjaxResult getPracticables(String matterId) {
        List<Map<String, Object>> indexList = workMatterService.getPracticables(matterId);
        return success(indexList);
    }

    @GetMapping("/getReports")
    public AjaxResult getReports(String matterId) {
        List<WorkReport> indexList = workMatterService.getReports(matterId);
        return success(indexList);
    }

    @GetMapping("/queryById/{matterId}")
    public AjaxResult queryById(@PathVariable("matterId") Integer matterId) {
        return success(workMatterService.queryById(matterId));
    }

    /**
     * 删除事项
     */
    @PostMapping("/deleteById")
    public AjaxResult deleteById(@RequestBody Long[] matterIds)
    {
        return workMatterService.deleteMatterIds(matterIds) > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 修改事项
     */
    @PostMapping("/updateMatter")
    public AjaxResult updateMatter(@RequestBody WorkMatter workMatter) {
        return success(workMatterService.update(workMatter));
    }

    /**
     * 创建事项
     */
    @PostMapping("/add")
    @Transactional
    public AjaxResult add(@RequestBody AddWorkMatterRequest request) throws InvocationTargetException, IllegalAccessException {
        WorkMatter workMatter = new WorkMatter();
        BeanUtils.copyProperties(workMatter, request);
        workMatter.setStat(0);
        workMatter.setCreateTime(new Date());
        workMatterService.insert(workMatter);

        // 更新任务或者指标状态
//        String relatedIndicatorOrTaskType = request.getRelatedIndicatorOrTaskType();
//        Integer relatedIndicatorOrTaskId = request.getRelatedIndicatorOrTaskId();

//        if("0".equals(relatedIndicatorOrTaskType)){ // 指标
//            workMatterService.update
//        }

//        if("1".equals(relatedIndicatorOrTaskType)){ // 任务
//            workMatterService.updateTaskStat(relatedIndicatorOrTaskId);
//        }

//        Integer matterId = workMatter.getMatterId();
//        List<WorkContent> workContents = request.getWorkContentList();

//        if (workContents.size() > 0) {
//            workContents.stream().map(
//                    workContent -> {
//                        workContent.setStat(0);
//                        workContent.setMatterId(matterId);
//                        workContent.setCreateTime(new Date());
//                        return workContent;
//                    }
//            ).collect(Collectors.toList());
//            workContentService.insertBatch(workContents);
//        }
//
//        List<WorkCollaboration> workCollaborations = request.getWorkCollaborationList();
//        if (workCollaborations.size() > 0) {
//            workCollaborations.stream().map(
//                    workCollaboration -> {
//                        workCollaboration.setStat(0);
//                        workCollaboration.setMatterId(matterId);
//                        workCollaboration.setCreateTime(new Date());
//                        return workCollaboration;
//                    }
//            ).collect(Collectors.toList());
//            workCollaborationService.insertBatch(workCollaborations);
//        }
        return success();
    }

    @GetMapping("/getMatterList")
    public AjaxResult getMatterList() {
        return workMatterService.getMatterList();
    }


    @GetMapping(value = "/{sid}")
    public AjaxResult getInfo(@PathVariable("sid") Integer sid)
    {
        return workMatterService.getInfo(sid);
    }


    /**
     * 催办
     */
    @PostMapping("/addDialog")
    @Transactional(rollbackFor = RuntimeException.class)
    public AjaxResult addDialog(@RequestBody WorkDialog workDialog) {
        Long userId = SecurityUtils.getUserId();
        workDialog.setDialogUserId(userId.intValue());
        workDialog.setCreateTime(new Date());
        workDialogService.insert(workDialog);
        WorkMatter workMatter = new WorkMatter();
        workMatter.setMatterId(workDialog.getMatterId());
        workMatter.setEm5("1");
        workMatterService.update(workMatter);
        return success();
    }

    /**
     * @author zhouzhanwei
     * @date 2024/7/9 16:13
     * 保存落实情况
     */
    @PostMapping("/saveWorkImplementation")
    public AjaxResult saveWorkImplementation(@RequestBody SystemManageVo systemManageVo){

    return workMatterPracticableService.saveWorkImplementation(systemManageVo);
    }

    /**
     * @author zhouzhanwei
     * @date 2024/7/9 16:13
     * 保存节点、协同
     */
    @PostMapping("/saveContentAndColl")
    public AjaxResult saveContentAndColl(@RequestBody SystemManageVo systemManageVo){

        return workMatterPracticableService.saveContentAndColl(systemManageVo);
    }

    @PostMapping("/saveWorkReport")
    public AjaxResult saveWorkReport(@RequestBody WorkReport workReport){
        return workReportService.saveWorkReport(workReport);
    }

    @GetMapping("/getWorkReportInfo/{sid}")
    public AjaxResult getWorkReportInfo(@PathVariable("sid") Integer sid){
        return workReportService.getWorkReportInfo(sid);
    }

    @DeleteMapping("/delWorkReportInfo/{sid}")
    public AjaxResult delWorkReportInfo(@PathVariable("sid") Integer sid){
        return workReportService.delWorkReportInfo(sid);
    }

    @GetMapping("/getWorkReportByMatterId/{matterId}")
    public AjaxResult getWorkReportByMatterId(@PathVariable("matterId") Integer matterId){
        return workReportService.getWorkReportByMatterId(matterId);
    }

    /**
     * 查询我负责的任务
     */
//    @GetMapping("/getMyMatterPage")
//    public AjaxResult getMyMatterPage(@RequestParam Map<String,Object> map) {
//        JSONObject params = new JSONObject(map);
//        PageInfo<WorkMatter> indexList = workMatterService.getMyMatterPage(params);
//        return AjaxResult.success(indexList);
//    }

    /**
     * 查询我负责的任务
     */
    @GetMapping("/getMyMatterPage")
    public AjaxResult getMyMatterPage(WorkMatter matter, PageDomain pageDomain) {
        Long userId = SecurityUtils.getUserId();
        matter.setMatterResponsibleId(userId.intValue());
        matter.setUserId(userId);
        PageInfo<WorkMatter> indexList = workMatterService.getIndexList(matter, pageDomain);
        return success(indexList);
    }

    /**
     * 事项认领
     */
    @GetMapping("/matterClaim")
    public AjaxResult matterClaim(@RequestParam Map<String,Object> params) {
        workMatterService.matterClaim(params);
        return success();
    }

    /**
     * 获取我的督办
     */
    @GetMapping("/getMyDialog")
    public AjaxResult getMyDialog(@RequestParam Map<String,Object> params) {
       return workDialogService.getMyDialog(params);
    }

}
